package com.etrans.web.gps.business.system.controller;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.ThreadLocalRandom;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.etrans.egov.base.cmd.obj.CmdArgsPostQueryReq;
import com.etrans.egov.base.cmd.obj.CmdIds;
import com.etrans.egov.base.cmd.obj.ObjCmdReceipt;
import com.etrans.egov.base.cmd.obj.ObjCmdReply;
import com.etrans.egov.base.cmd.obj.ObjCmdRequest;
import com.etrans.egov.base.packet809.Packet;
import com.etrans.egov.base.packet809.uitls.Packet809Utils;
import com.etrans.web.gps.base.controller.BaseController;
import com.etrans.web.gps.business.base.domain.EnterpriseVO;
import com.etrans.web.gps.business.base.domain.PlatformVO;
import com.etrans.web.gps.business.base.service.EnterpriseService;
import com.etrans.web.gps.business.base.service.PlatformService;
import com.etrans.web.gps.business.command.controller.Net2CmdProducer;
import com.etrans.web.gps.business.system.domain.CheckType;
import com.etrans.web.gps.business.system.domain.EntCheck;
import com.etrans.web.gps.business.system.domain.EntCheckCmd;
import com.etrans.web.gps.business.system.domain.QueryEntCheck;
import com.etrans.web.gps.business.system.domain.Strategy;
import com.etrans.web.gps.business.system.domain.SysUser;
import com.etrans.web.gps.business.system.service.CommonService;
import com.etrans.web.gps.business.system.service.EntCheckService;
import com.etrans.web.gps.common.Constant;
import com.etrans.web.gps.common.page.PageResultVo;
import com.etrans.web.gps.common.page.PageVo;
import com.etrans.web.gps.util.Config;
import com.etrans.web.gps.util.grid.FlexiGridUtil;

/**
 *	业户查岗
 * @author jw.chen
 *
 */
@Controller
@RequestMapping("/system/entCheck/*")
public class EntCheckController extends BaseController {
	
	private static final Logger logger = LoggerFactory.getLogger(EntCheckController.class);

	
	@Autowired
	private EntCheckService entCheckService;
	
	@Autowired
	private EnterpriseService enterpriseService;
	
	@Autowired
	private PlatformService platformService;
	
	@Autowired
	private CommonService commonService;
	
	@Autowired
	private Config config; //引用统一的参数配置类
	
	
	// 跳转到业户查岗页面
	@RequestMapping(value = "toEntCheck.html")
	public ModelAndView toEntCheck(HttpServletRequest request, Model model) {
		ModelAndView mnv = new ModelAndView();
		mnv.setViewName("views/business/system/entCheck/queryEntCheck");
		return mnv;
	}
	
	/**
	 * 业户查岗策略设置
	 * @return
	 */
	@RequestMapping(value = "initStrategys.html")
	public ModelAndView initStrategys() {
		ModelAndView mav = new ModelAndView();
		mav.setViewName("views/business/system/entCheck/addEntStrategyForm");
		return mav;
	}
	
	/**
	 * 业户查岗记录查询
	 * @param paramsGrid 
	 */
	@RequestMapping(value="loadAllEntChecks.html")
	@ResponseBody
	public PageVo queryEntCheckList(@RequestParam String paramsGrid){
		logger.info("{}{}:::::::查询业户查岗记录方法进入::::::::{}{}");
		PageVo page = new PageVo();
		Map<String, Object> paramMap = FlexiGridUtil.parseJSONParam(paramsGrid).getWhereParam();
		
		List<QueryEntCheck> list = new ArrayList<>();
		try {	
			// 添加数据权限 ->当前登录用户对应的所有业户id
			HashMap<String, Object> param = new HashMap<>();
			SysUser user=getSysUser();
			param.put("FullID", String.format("%08d", user.getArea_id()));
			List<HashMap<String, Object>> listCheckUnitIds = commonService.selectEnterprise(param);
			paramMap.put("listCheckUnitIds", listCheckUnitIds);
			// 添加数据权限
			
			// 查询结果
			list = entCheckService.queryEntCheckList(paramMap);
			
			logger.info("{}{}:::::::查询业户查岗记录条数::::::::{}{}", list.size());
			page.setRows(list);
			page.setPage((int) paramMap.get("page"));
			page.setTotal(entCheckService.queryEntCheckListCount(paramMap));
			
		} catch (Exception e) {
			logger.error("加载用户失败", e);
			e.printStackTrace();
		}
		return page;
	}
	/**
	 * 业户策略设置记录查询
	 * @param paramsGrid
	 * @return
	 */
	@SuppressWarnings("unused")
	@RequestMapping(value="loadAllStrategys.html")
	public void queryEntAllStrategys(HttpServletResponse response,HttpServletRequest request,@RequestParam String paramsGrid){
		Map<String, Object> params = FlexiGridUtil.parseJSONParam(paramsGrid).getWhereParam();
		try {
			// 业户ids
			String entIds = "";
			entIds = params.get("selectEntModels") == null ? "" : params.get("selectEntModels").toString();
			if(entIds!= null && !entIds.equals("")){
				params.put("entIds", entIds);
			}else{
				logger.info("==============>界面查询条件【业户】下拉id为空<==========================");
			}
			
			// 区域Ids
			String areaIds = params.get("selectAreaModels") == null ? "" : params.get("selectAreaModels").toString();
			HashMap<String, List<Integer>> where_areaIds = new HashMap<>();	
			List<Integer> listAreaIds = new ArrayList<>();
			if(areaIds!= null && !areaIds.equals("")){
				String [] selectAreaModels = areaIds.split(",");
				for (String string : selectAreaModels) {
					listAreaIds.add(Integer.valueOf(string));
				}
			}else{
				logger.info("==============>界面查询条件【区域】下拉id为空<==========================");
			}
			
			// 如果区域ids不为空，则根据区域ids查询对应的所有业户ids
			if(listAreaIds != null && listAreaIds.size() > 0 ){
				List<HashMap<String, Object>> list = commonService.queryEnterpriseByIds(listAreaIds);
				if(list != null && list.size() > 0){
					for (HashMap<String, Object> hashMap : list) {
						entIds = entIds + hashMap.get("ID").toString()+",";
					}
				}else{
					logger.info("==============>根据区域id查询对应业户id为空<==========================");
				}
				
				logger.info("==============>根据区域id查询对应业户id拼接前：<=========================="+entIds);
				logger.info("==============>根据区域id查询对应业户id截取后：<=========================="+entIds.substring(0, entIds.length()-1));
				params.put("entIds", entIds.substring(0, entIds.length()-1));
			}
			
			// 查岗时间特例
			if(params.get("queryCheckTime")!=null && !params.get("queryCheckTime").equals("")){
				params.put("queryCheckTime", params.get("queryCheckTime")+":00");
			}
			
			// 添加数据权限 ->当前登录用户对应的所有业户id
			HashMap<String, Object> param = new HashMap<>();
			SysUser user = getSysUser();
			param.put("FullID", String.format("%08d", user.getArea_id()));
			List<HashMap<String, Object>> listCheckUnitIds = commonService.selectEnterprise(param);
			String checkTargetIds = "";
			if (listCheckUnitIds != null && listCheckUnitIds.size() > 0) {
				for (HashMap<String, Object> hashMap : listCheckUnitIds) {
					// 当前登录用户对应的所有业户id
					checkTargetIds = checkTargetIds + hashMap.get("id").toString()+",";
				}
				params.put("checkTargetIds", checkTargetIds.substring(0,checkTargetIds.length()-1));
			} else {
				logger.info("当前登录人查询区域查岗记录操作---->数据权限---->当前登录人没有区域对应的区域id step1");
			}
			List<Strategy> rows = entCheckService.queryEntAllStrategys(params);
			Long total = entCheckService.entAllStrategysCount(params);
			PageVo pageBean = new PageVo();
			pageBean.setRows(rows);
			pageBean.setPage((int) params.get("page"));
			pageBean.setTotal(total.intValue());
			ajaxResultJson(response,pageBean);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * 
	 * @param response
	 * @param questionIds
	 */
	@RequestMapping(value="deleteStrategy.html")
	public void deleteStrategy(HttpServletResponse response,String strategyIds){
		PageResultVo pr = new PageResultVo();
		try {
			strategyIds=strategyIds.replaceAll("row", "");
			if(strategyIds != null && !"".equals(strategyIds)){
				String[] strategyId = strategyIds.split(",");
				for (String s : strategyId) {
					entCheckService.deleteStrategy(Integer.parseInt(s));
				}
			}
			pr.setCode(Constant.RETURN_OK_CODE);
		} catch (Exception e) {
			e.printStackTrace();
			pr.setCode(Constant.RETURN_ERROR_CODE);
			pr.setMsg("删除失败!");
		}
		
		ajaxResultJson(response, pr);
	}
	

	/**
	 * 业户查岗策略保存
	 * @param request
	 * @param response
	 * @param strategy
	 */
	@SuppressWarnings("null")
	@RequestMapping(value = "saveStrategy.html")
	public void saveStrategy(HttpServletRequest request, HttpServletResponse response, String checkTime,
			String questionId, String question,String checkMode, String[] checkTargetId,String answer) {
		SimpleDateFormat format1 = new SimpleDateFormat("yyyy-MM-dd");
		PageResultVo pr = new PageResultVo();
		try {
			
			// 获取当前登录对象
			SysUser user = (SysUser)getSession().getAttribute(Constant.LOGIN_SESSION_NAME);
			
			// 自动-> 插入策略设置表->定时任务循环策略表->发指令->插入MONGODB区域查岗记录表
			if(checkMode.equals("1")){
				
				// 业户id数组循环
				if(checkTargetId.length > 0){
					
					for (String targerId : checkTargetId) {
						// 策略设置数据封装
						Strategy strategy = new Strategy();
						// 查岗类型： 1：业户 2：区域（即管理机构） 
						strategy.setCheckType(1);
						// 查岗对象  如果 查岗类型是业户时，此处是业户的ID、查岗类型是区域时，此处是区域的ID,
						strategy.setCheckTargetId(Integer.valueOf(targerId)); 
						// 题库id
						strategy.setQuestionId(Integer.valueOf(questionId));
						
						// 查岗时间->系统年 月 日+界面的 时 分 秒
						strategy.setCheckTime(format1.format(new Date())+" "+checkTime);
						
						// 查岗人
						String userName = user.getUser_name();
						strategy.setUserName(userName);
						
						// 保存方法调用
						entCheckService.saveStrategy(strategy);
					}
				}
			
				else{
					logger.info("=======自动=======》entCheck.js =============》传入后台业户查岗下拉id 为空: {}");
				}
				pr.setCode(Constant.RETURN_OK_CODE);
			}
			// 手动->直接发指令->插入MONGODB业户查岗表、业户查岗指令表
			if(checkMode.equals("2")){
				
				
				// 业户id数组循环
				if(checkTargetId.length > 0){
					
					// commander 连接
					Net2CmdProducer cmdProducer = new Net2CmdProducer(config.commanderPath, config.commanderPort);
					
					cmdProducer.start();
					
					// 判断commander 连接是否成功
					if(cmdProducer.getClient().isConnected()){

						for (String targerId : checkTargetId) {
							
							
							int enterpriseId = Integer.valueOf(targerId);
							// 根据业户id 查询 平台接入id
							EnterpriseVO enterpriseVO = enterpriseService.queryEnterpriseById(enterpriseId);
							
							int gnss_center_id = 0;
							if(enterpriseVO != null){
								// 平台接入id
								int platformId = enterpriseVO.getPlatformId();
								PlatformVO platformVO = platformService.queryPlatformById(platformId);
								if(platformVO != null){
									gnss_center_id = platformVO.getAccessCenterCode();
								}else{
									logger.info("无法获取平台接入码 platformVO.getAccessCenterCode(): {}", platformVO.getAccessCenterCode());
								}
								
							}else{
								logger.info("无法获取获取平台接入id: enterpriseVO.getPlatformId(){}", enterpriseVO.getPlatformId());
							}
							
					
							int object_type = CheckType.CHECK_TYPE_TWO;
							// 查岗id
							int info_id = ThreadLocalRandom.current().nextInt();
							// 为业户经营许可证号
							String object_id = enterpriseVO.getBizLicenseNum().trim(); 
							
							// 数据包封装
							CmdArgsPostQueryReq cmdArgsPostQueryReq = new CmdArgsPostQueryReq();
							cmdArgsPostQueryReq.setGnssCenterId(gnss_center_id);				// 平台接入id
							cmdArgsPostQueryReq.setObjectType((byte) object_type);
							cmdArgsPostQueryReq.setObjectId(object_id);							// 下发的业户id
							cmdArgsPostQueryReq.setInfoId(info_id);								// 查岗id
							cmdArgsPostQueryReq.setInfoContent(question);						// 题库问题名称

							logger.info("cmdArgsPostQueryReq: {}", cmdArgsPostQueryReq.toJSONObject());

							ObjCmdRequest objCmd = new ObjCmdRequest();
							objCmd.setCmdId(CmdIds.CMD_ID_POST_QUERY_REQ);
							objCmd.setArgs(cmdArgsPostQueryReq.toJSONObject().toString());
							objCmd.setReceiptTimeout(5000);
							objCmd.setReplyTimeout(1000 * 60 * 15);
							try {
								cmdProducer.push(objCmd, new Net2CmdProducer.Callback() {
									@Override
									public void onObjCmdReceipt(ObjCmdReceipt objCmdReceipt) throws Exception {
										logger.info("onObjCmdReceipt: {}", objCmdReceipt.toJSONObject());
										System.out.println("aaaaa");
									}

									@Override
									public void onReceiptTimeout() throws Exception {
										logger.info("onReceiptTimeout");
										System.out.println("bbbbbb");
									}

									@Override
									public void onObjCmdReply(ObjCmdReply objCmdReply) throws Exception {
										logger.info("onObjCmdReply: {}", objCmdReply.toJSONObject());
										Packet packet = Packet809Utils.makePacketFromDecodedBytes(objCmdReply.getRawData(), true);
										logger.info("packet: {}", packet.toJSONObject());
									}

									@Override
									public void onReplyTimeout() throws Exception {
										logger.info("onReplyTimeout");
										System.out.println("ccccccc");
									}
								});
							} catch (Exception e) {
								System.out.println("11111111111");
							}
							
							
							Date check_time  = new Date();
							// 保存post_check表
							String _id = UUID.randomUUID().toString().replace("-", "");
							EntCheck entCheck = new EntCheck();
							entCheck.set_id(_id);											// check_id UUID
							entCheck.setChecker(user.getUser_name());						// 查岗人
							entCheck.setCheck_time(check_time);								// 查岗时间
							entCheck.setCheck_content(question);							// 查岗内容
							entCheck.setAnswer(answer);										// 答案
							entCheck.setCheck_type(1); 										// 查岗方式  1:手动  2:自动
							entCheck.setTotal_count(1);										// 总查岗指令数
							entCheck.setSucc_reply_count(0);								// 成功回复指令数
							entCheck.setFail_reply_count(0);								// 失败回复指令数
							entCheck.setNo_reply_count(1);									// 无回复指令数

							// 保存MONGODB
							entCheckService.insertEntCheckToMongodb(entCheck);
							
							// 保存post_check_cmd表
							EntCheckCmd entCheckCmd = new EntCheckCmd();
							entCheckCmd.set_id(object_type+":"+object_id+":"+info_id);  // <object_type:object_id:info_id>
							entCheckCmd.setCheck_id(_id); 								// post_check 表 _id UUID
							entCheckCmd.setCheck_unit_id(Integer.valueOf(targerId));	// 查岗业户ID
							entCheckCmd.setCheck_unit_name(enterpriseVO.getName());		// 查岗业户名称
							entCheckCmd.setInfo_id(info_id); 							// 查岗指令info_id随机数
							entCheckCmd.setObject_id(object_id);
							entCheckCmd.setCheck_time(check_time); 						// 查岗时间
							entCheckCmd.setCheck_result(4);								// 查岗结果 1:正确 2:错误 3:超时 4:未应答  (默认4:未应答)
							entCheckCmd.setCheck_content(question);						// 查岗内容
							entCheckCmd.setAnswer(answer);								// 答案
							// 保存MONGODB
							entCheckService.insertEntCheckCmdToMongodb(entCheckCmd);
							pr.setCode(Constant.RETURN_OK_CODE);
						}
					}else{
						pr.setCode(Constant.SEND_CMD_TIME_OUT);
					}
					
					// 所有逻辑执行完后 关闭链接
					cmdProducer.getClient().closeResources();// 关闭链接
					
				}
				else{
					logger.info("=======手动=======》entCheck.js =============》传入后台业户查岗下拉id 为空: {}");
				}
			
			}
			
			
			
		} catch (Exception e) {
			e.printStackTrace();
			pr.setCode(Constant.RETURN_ERROR_CODE);
			pr.setMsg("保存失败!");
		}
		
		ajaxResultJson(response, pr);
	}
	
	
	/**
	 * 业户查岗记录导出
	 * @param request
	 * @param response
	 * @param queryParams
	 * @param title
	 * @param StartPage
	 * @param EndPage
	 * @param PageSize
	 * @param sortorder
	 * @param colModel
	 */
	@SuppressWarnings({ "unchecked", "rawtypes" })
	@RequestMapping(value = "exportEntChecks.html")
	public void exportEntChecks( HttpServletRequest request, HttpServletResponse response, String queryParams, 
			String title, String StartPage, String EndPage, String PageSize,String colModel,String sortorder) {
		
		//获取参数
		HashMap<String, Object> params = new HashMap<String, Object>();
		List<String> colModelList = JSON.parseObject(colModel, List.class);
		try {
			Map<String, Object> paramMap = getReqParameters();
			List<String> whereParamsList = JSON.parseObject(paramMap.get("queryParams").toString(), List.class);
			for (Object object : whereParamsList) {
				JSONObject jsonObject = (JSONObject) object;
				params.put(jsonObject.get("name").toString(), jsonObject.get("value"));
			}
			// 分页条件
			int startPage = Integer.parseInt(StartPage);
			int endPage   = Integer.parseInt(EndPage);
			int pageSize  = Integer.parseInt(PageSize);
			params.put("page", startPage);
			params.put("pageSize", (endPage - startPage + 1) * pageSize);
			params.put("sortorder", sortorder); // 排序方式
			
			//传入条件从MongoDB中查询出数据
			List<QueryEntCheck> list = entCheckService.queryEntCheckList(params);	
			List<HashMap<String, Object>> rows = new ArrayList<HashMap<String, Object>>();
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			
			for (QueryEntCheck queryEntCheck : list) {
				HashMap<String, Object> map = new HashMap<String, Object>();
				map.put("check_unit_name", queryEntCheck.getCheck_unit_name() == null ? "" : queryEntCheck.getCheck_unit_name().toString());
				map.put("check_time", 	   sdf.format(queryEntCheck.getCheck_time()));
				map.put("check_content",   queryEntCheck.getCheck_content() == null ? "" : queryEntCheck.getCheck_content().toString());
				map.put("answer", 		   queryEntCheck.getAnswer() == null ? "" : queryEntCheck.getAnswer().toString());
				Date replyTime = queryEntCheck.getReply_time();
				if(replyTime!=null){
					map.put("reply_time",   sdf.format(queryEntCheck.getReply_time()));
				}else{
					map.put("reply_time",    "");
				}
				map.put("reply_content",   queryEntCheck.getReply_content() == null ? "" : queryEntCheck.getReply_content().toString());
				map.put("check_type", 	   queryEntCheck.getCheck_type()== 1 ? "手动" : "自动");
				map.put("check_result",    getCheckResult(queryEntCheck.getCheck_result()));
				rows.add(map);
			}
			int index = -1;
			List rowsList = new ArrayList<>();
			rowsList.add(rows);
			exportExl(request, response, title, removeHeadName(colModelList, index, -1), rowsList, null);
			
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("业户查岗导出败",e);
			
		}		
		
	}
	/**
	 * 转换名称
	 * @param check_result
	 * @return
	 */
	public String getCheckResult(int check_result){
		
		if(check_result == 1){
			return "正确";
		}
		else if(check_result == 2){
			return "错误";
		}
		else if(check_result == 3){
			return "超时";
		}
		else{
			return "未应答";
		}
	}

	
}
